package org.dyz.banana.platform.sample.eurakaclient2.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonController {

	@Resource(name="ribbonRestTemplate")
	RestTemplate restTemplate;
	
	@Autowired
	private LoadBalancerClient loadBalancer;
	
	
	/**
	 * 获取eurakaclientsample1服务信息
	 * @return
	 */
	@GetMapping("/sample2/choose")
	public Object chooseUrl() {
	    ServiceInstance instance = loadBalancer.choose("eurakaclientsample1");
	    return instance;
	    /*返回如下信息：
	     * {
		    serviceId: "eurakaclientsample1",
		    server: {
		        host: "localhost",
		        port: 8081,
		        id: "localhost:10000",
		        zone: "UNKNOWN",
		        readyToServe: true,
		        alive: true,
		        hostPort: "localhost:10000",
		        metaInfo: {
		            serverGroup: null,
		            serviceIdForDiscovery: null, instanceId: "localhost:10000",
		            appName: null
		        }
		    },
		    secure: false, metadata: { }, host: "localhost", port: 10000,
		    uri: "http://localhost:10000"
		}*/
	}
	
	/****************************当RestTemplate添加了@LoadBalance时 Start*************************************/
	
	@GetMapping("/sample2/getData")
	public String getData(@RequestParam("name")String name) {
		return restTemplate.getForObject("http://eurakaclientsample1/sample/getData?name="+name, String.class);
	}
	
	@GetMapping("/sample2/getData/{name}")
	public String getData2(@PathVariable("name")String name) {
		return restTemplate.getForObject("http://eurakaclientsample1/sample/getData/{name}", String.class,name);
	}
	
	@PostMapping("/sample2/setData")
	public String setData(@RequestParam("name")String name) {
		return restTemplate.getForObject("http://eurakaclientsample1/sample/setData?name="+name, String.class);
	}
	
	@PostMapping("/sample2/setData/{name}")
	public String setData2(@PathVariable("name")String name) {
		return restTemplate.getForObject("http://eurakaclientsample1/sample/setData/{name}", String.class,name);
	}
	
	/****************************当RestTemplate添加了@LoadBalance时 End*************************************/
	
	
	
	
	
}
